package cn.doyo.spring.test.factorybean;

import cn.duyo.spring.beans.factory.FactoryBean;
import net.sf.cglib.proxy.InvocationHandler;
import net.sf.cglib.proxy.Proxy;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author du
 */
public class UserDaoFactoryBean implements FactoryBean<IUserDao> {


    /**
     * 类似于 MyBatis 框架中的代理操作;
     * getObject() 中提供的就是一个 InvocationHandler 的代理对象，当有方法调用的时候，则执行代理对象的功能
     */
    @Override
    public IUserDao getObject() throws Exception {

        /**
         * InvocationHandler: FastClass机制
         * MethodInterceptor: 兼容JDK, 反射方式
         */
        InvocationHandler handler = (proxy, method, args) -> {

            Map<String, String> hashMap = new HashMap<>();
            hashMap.put("10001", "张三");
            hashMap.put("10002", "李四");
            hashMap.put("10003", "王五");

            return "你被代理了 " + method.getName() + "：" + hashMap.get(args[0].toString());
        };

        /*InvocationHandler handler1 = new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                Map<String, String> hashMap = new HashMap<>();
                hashMap.put("10001", "张三");
                hashMap.put("10002", "李四");
                hashMap.put("10003", "王五");
                method.invoke()
                return null;
            }
        };*/
        return (IUserDao) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{IUserDao.class}, handler);
    }

    @Override
    public Class<?> getObjectType() {
        return IUserDao.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
